package com.goldman.aplt.util;

import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Scope("singleton")
@Component
@Slf4j
public class ApRedisDistributeLock {

    @Autowired
    private RedissonClient redisson;

    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) {
        try {
            return redisson.getLock(lockKey).tryLock(waitTime, leaseTime, unit);
        }
        catch (InterruptedException e) {
            log.error("Acquire redis lock of %s failed, ocurrs multi-thread campaigns, detail infos: %s.", lockKey, e);
            return false;
        }
    }

    /**
     * @Author zouqichang
     *         <p>
     *         <li>Nov 16, 2020-2:49:41 PM</li>
     *         <li>功能说明：锁定lock key对应的锁</li>
     *         </p>
     * @param lockKey
     *            锁的key
     * @param leaseTime
     *            持有锁的时间
     * @param unit
     *            时间单位
     */
    public void lock(String lockKey, long leaseTime, TimeUnit unit) {
        redisson.getLock(lockKey).lock(leaseTime, unit);
    }

    /**
     * @Author zouqichang
     *         <p>
     *         <li>Nov 16, 2020-2:50:25 PM</li>
     *         <li>功能说明：释放锁</li>
     *         </p>
     * @param lockKey
     */
    public void unlock(String lockKey) {
        RLock lock = redisson.getLock(lockKey);
        if (lock.isLocked()) { // 是否还是锁定状态
            if (lock.isHeldByCurrentThread()) { // 是当前执行线程的锁
                lock.unlock(); // 释放锁
            }
        }
    }

    public void unlockForce(String lockKey) {
        RLock lock = redisson.getLock(lockKey);
        if (lock.isLocked()) { // 是否还是锁定状态
            lock.forceUnlock(); // 释放锁
        }
    }

}